package com.chinasofti.user.controller;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chinasofti.user.domain.User;
import com.chinasofti.user.service.UserService;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/user/loginView")
	public String loginView(){
		return "login/login";
	}
	
	@RequestMapping("/user/registerView")
	public String registerView(){
		return "register";
	}
	
	@RequestMapping(value="/user/login")
	public String login(User user,ServletRequest request,HttpSession session){
		User u = userService.findUserByUserName(user);
		if(null==u){
			request.setAttribute("errMsg", "用户名或密码错误");
			return "/login/login";
		}
		else{
			session.setAttribute("user", u);
			return "redirect:/index/index.do";
			
		}
	}
	
	@RequestMapping("/user/register")
	public String register(User user,ServletRequest request,HttpSession session){
		JSONObject result = userService.save(user);
		if(result.getBoolean("success")){
			User u = userService.findUserByUserName(user);
			if(null==u){
				request.setAttribute("errMsg", "用户名或密码错误");
				return "/login/login";
			}
			else{
				session.setAttribute("user", u);
				return "redirect:/index/index.do";
				
			}
		}
		else{
			request.setAttribute("errMsg", result.get("msg"));
			request.setAttribute("formCode", "registerForm");
			return "/login/login";
		}
	}
}